<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="params.username"
        placeholder="账户名"
        size="medium"
        clearable
        style="width: 300px;margin-right: 10px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="params.channelId" size="medium" class="filter-item" placeholder="请选择渠道名称" style="width: 300px" clearable v-if="userTypeCode != 2">
        <el-option
          v-for="item in channels"
          :key="item.id"
          :label="item.channelName"
          :value="item.id"
        />
      </el-select>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        size="medium"
        icon="el-icon-search"
        @click="handleFilter"
      >查询
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        size="medium"
        icon="el-icon-edit-outline"
        @click="handleCreate"
      >创建
      </el-button>
    </div>
    <el-table :data="list" border style="width: 100%" v-loading="listLoading">
      <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
      <el-table-column prop="username" label="登录账号" style="width: 30%" />
      <el-table-column prop="roleNames" label="角色" style="width: 30%" />
      <el-table-column prop="channelName" label="渠道名称" style="width: 30%" />
      <el-table-column prop="status" label="状态" :width='120'>
        <template slot-scope="{row}">
          <!-- <el-tag type="row.status">
            {{ blnStatus(row.status) }}
          </el-tag> -->
          <el-tag type="success" v-if='row.status == 1'>开启</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="channelCode" label="渠道编码" style="width: 30%" />
      <el-table-column fixed="right" label="操作" style="width: 30%">
        <template slot-scope="{row,$index}">
          <el-button type="success" size="mini" @click="handleView(row)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="params.page"
      :limit.sync="params.limit"
      @pagination="getList"
    />
    <!--编辑页面表单-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="channel-user-dialog">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="120px"
        style="margin: 0 40px;"
      >
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="form.username" :disabled="dialogStatus=='view' || dialogStatus=='update'" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus=='create'">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <template>
            <el-switch
              v-model="form.status"
              :disabled ='isDisabled'
              active-text="启用"
              inactive-text="禁用"
              active-value="1"
              inactive-value="2"
            />
          </template>
        </el-form-item>
        <el-form-item label="渠道名称" prop="channelCode" v-if="userTypeCode != '2'">
          <el-select v-model="form.channelCode" placeholder="请选择" :disabled="dialogStatus=='view'" style="width: 100%" @change="searchRole(1)">
            <el-option
              v-for="(item,index) in channels"
              :key="index"
              :label="item.channelName"
              :value="item.channelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds" v-if="form.channelCode">
          <el-select v-model="form.roleIds" placeholder="请选择" :disabled="dialogStatus=='view'" style="width: 100%">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template v-if="dialogStatus==='create'||dialogStatus==='update'">
        <div v-if="dialogStatus" slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { addOrModifyChannelUser, getChannelUserList, deleteChannelUser } from '@/api/channel/channelUser'
import Pagination from '@/components/Pagination'
import { getChannelList, getChannelRoles, getChannelRoleList } from '@/api/channel/channelRole'
export default {
  name: 'ChannelUser',
  components: { Pagination },
  data() {
    return {
      msg: '渠道用户',
      listLoading: false,
      list: [],
      total: 0,
      isDisabled: false,
      params: {
        id: '',
        username: '',
        password: '',
        channelCode: '',
        channelName: '',
        channelCode: '',
        roleIds: [],
        roleNames: '',
        page: 1,
        limit: 10
      },
      dialogStatus: '',
      roles: [],
      channels: [],
      form: {
        id: '',
        username: '',
        password: '',
        channelName: '',
        channelCode: '',
        status: 1,
        roleIds: ''
      },
      rules: {
        username: [{ required: true, message: '登录账号必填' }],
        password: [{ required: true, message: '密码必填' }],
        status: [{ required: true, message: '请选择用户状态' }],
        channelCode: [{ required: true, message: '请选择渠道名称' }],
        roleIds: [{ required: true, message: '请选择角色' }]
      },
      dialogFormVisible: false,
      textMap: {
        view: '详情',
        update: '编辑',
        create: '新增'
      },
      userTypeCode:''
    }
  },
  created() {
    this.getList()
    this.loadChannels()
    this.userTypeCode = sessionStorage.getItem("userTypeCode").substring(4,5)  || '';
  },
  methods: {
    resetTemp() {
      this.form = {
        id: '',
        timestamp: new Date(),
        status: '1',
      }
    },
    handleFilter() {
      this.params.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.loadRoles()
      if(this.userTypeCode == '2'){
        this.getChannelRoles();
      }
      // this.loadChannels()
      // this.form.status = 1
      this.isDisabled = false
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let roleIds = []
          roleIds.push(this.form.roleIds)
          this.form.roleIds = roleIds
          addOrModifyChannelUser(this.form).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      const element = this.list[index]
      const data = [element.id]
      this.$confirm('确定删除该条数据？','提示', {
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteChannelUser(data).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.handleFilter()
        })
      }).catch(() => {
                
      });
    },
    handleView(row) {
      this.isDisabled = true
      this.form = Object.assign({}, row) // copy obj
      this.form.timestamp = new Date(this.form.timestamp)
      this.dialogStatus = 'view'
      this.form.status = this.form.status + '';
      this.form.roleIds = this.form.roleIds[0];
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.loadRoles()
      if(this.userTypeCode == '2'){
        this.getChannelRoles();
      }
      if(this.userTypeCode == '1'){
        this.searchRole();
      }
      // this.loadChannels()
    },
    handleUpdate(row) {
      this.isDisabled = false
      this.form = Object.assign({}, row) // copy obj
      this.form.timestamp = new Date(this.form.timestamp)
      this.form.status = this.form.status + ''
      this.form.roleIds = this.form.roleIds[0];
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.loadRoles()
      if(this.userTypeCode == '2'){
        this.getChannelRoles();
      }
      if(this.userTypeCode == '1'){
        this.searchRole();
      }
      // this.loadChannels()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let roleIds = []
          roleIds.push(this.form.roleIds)
          this.form.roleIds = roleIds
          const tempData = Object.assign({}, this.form)
          addOrModifyChannelUser(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.list.splice(index, 1, this.form)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      getChannelUserList(this.params).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    blnStatus(status) {
      return status === 1 ? '开启' : '停用'
    },
    loadRoles() {
      // getChannelRoles().then(response => {
      //   this.roles = response.data
      //   console.log('3333',response.data)
      // })
    },
    loadChannels() {
      getChannelList().then(response => {
        this.channels = response.data
      })
    },
    //當前渠道下的用戶角色
    searchRole(num){
      let channelId = ''
      this.channels.forEach( v=>{
        if(v.channelCode == this.form.channelCode){
          channelId = v.id
        }
      })
      getChannelRoleList({channelId: channelId,limit: 9999, page: 1}).then(response => {
        this.roles = response.data.records
        //切换渠道名称的时候清空所选角色
        if(num == 1 && this.dialogStatus == 'update'){
          this.form.roleIds = ''
        }
      })
    },
    //渠道用户获取当前渠道下的角色
    getChannelRoles(){
      this.form.channelCode = sessionStorage.getItem("channelCode") || ''
      this.searchRole()
    }
  }
}
</script>

<style lang="scss">
  .channel-user-dialog .el-dialog{
    width: 26%
  }
  .channel-user-dialog .el-dialog__footer{
    text-align: center
  }
  .channel-user-dialog .el-dialog__body{
    padding: 30px 20px 20px 20px;
  }
</style>
